import config from '../config'
import game from '../game'
import levelData from '../data/level'
import util from '../util'

export default class {
  constructor(data) {
    this.alive = true
    this.attribute = data
    this.idle = {
      nextActionTick: 0
    }
    this.search = {
      nextActionTick: 0
    }
    this.fight = {
      nextActionTick: 0
    }
  }

  get hpPercent() {
    return (this.attribute.hp.current / this.attribute.hp.max) * 100
  }

  get mpPercent() {
    return (this.attribute.mp.current / this.attribute.mp.max) * 100
  }

  get expPercent() {
    return Math.round((this.attribute.exp.current / this.attribute.exp.max) * 10000) / 100
  }

  updateIdleNextActionTick(tickCount) {
    this.idle.nextActionTick = tickCount + config.fps
  }

  updateSearchNextActionTick(tickCount) {
    this.search.nextActionTick = tickCount + config.searchInterval / 1000 * config.fps
  }

  updateFightNextActionTick(tickCount) {
    this.fight.nextActionTick = tickCount + Math.round(this.attribute.aspd / 1000 * config.fps)
  }

  addAttributeExp(count) {
    let ObtainExp = count
    if (this.attribute.level === config.maxLevel && count > this.attribute.exp.max - this.attribute.exp.current) {
      ObtainExp = this.attribute.exp.max - this.attribute.exp.current
    }

    let expAddResult = this.attribute.exp.current + count

    while (this.attribute.level + 1 <= config.maxLevel && expAddResult >= this.attribute.exp.max) {
      expAddResult = expAddResult - this.attribute.exp.max
      this.levelUp()
    }

    if (this.attribute.level === config.maxLevel && expAddResult >= this.attribute.exp.max) {
      expAddResult = this.attribute.exp.max
    }

    this.attribute.exp.current = expAddResult

    return ObtainExp
  }

  reduceAttributeExp(count) {
    if (this.attribute.exp.current - count < 0) {
      let reduce = this.attribute.exp.current
      this.attribute.exp.current = 0
      return reduce
    }
    else {
      this.attribute.exp.current = this.attribute.exp.current - count
      return count
    }
  }

  reduceAttributeHp(count) {
    if (this.attribute.hp.current - count <= 0) {
      this.attribute.hp.current = 0
      this.alive = false
    }
    else {
      this.attribute.hp.current = this.attribute.hp.current - count
    }
  }

  levelUp() {
    this.attribute.level = this.attribute.level + 1
    this.attribute.hp.current = this.attribute.hp.max = levelData['level' + this.attribute.level].hpBase
    this.attribute.mp.current = this.attribute.mp.max = levelData['level' + this.attribute.level].mpBase
    this.attribute.exp.max = levelData['level' + this.attribute.level].expMax
    this.attribute.atk = levelData['level' + this.attribute.level].atkBase
  }
}